using zhwy.saas.api.Entity.Other;
using zhwy.saas.api.Extensions.Log;
using zhwy.saas.api.Models.Other.Images;
using zhwy.saas.api.Repository;
using zhwy.saas.api.Services.Sinterface.Other;

namespace zhwy.saas.api.Services.Other
{
    public class ImagesService : BaseService<ImagesEntity>, IImagesService
    {
        private readonly IWebHostEnvironment _webHostEnvironment;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository">菜单仓储接口</param>
        /// <param name="logger">日志服务</param>
        /// <param name="webHostEnvironment">web环境服务</param>
        public ImagesService(IBaseRepository<ImagesEntity> repository, ILogExt logger, IWebHostEnvironment webHostEnvironment)
            : base(repository, logger)
        {
            _webHostEnvironment = webHostEnvironment;
        }

        /// <summary>
        /// 添加图片信息
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <param name="userid">用户ID</param>
        /// <param name="tenantid">租户ID</param>
        /// <param name="sysUploadType">上传类型</param>
        /// <returns>图片信息</returns>
        public async Task<ImagesRes> AddImages(IFormFile file, long userid, int tenantid, string sysUploadType = null)
        {
            try
            {
                // 检查文件是否为空
                if (file == null || file.Length == 0)
                {
                    throw new ArgumentException("文件为空");
                }

                // 检查文件是否为图片
                string contentType = file.ContentType.ToLower();
                if (!contentType.StartsWith("image/"))
                {
                    throw new ArgumentException("文件不是图片类型");
                }

                // 获取文件扩展名
                string fileExtension = Path.GetExtension(file.FileName).ToLower();
                if (string.IsNullOrEmpty(fileExtension))
                {
                    // 从ContentType推断扩展名
                    fileExtension = contentType switch
                    {
                        "image/jpeg" => ".jpg",
                        "image/png" => ".png",
                        "image/gif" => ".gif",
                        "image/bmp" => ".bmp",
                        "image/webp" => ".webp",
                        _ => ".jpg"  // 默认使用jpg
                    };
                }

                // 创建保存目录结构 /wwwroot/userid/yyyymmdd/
                string wwwrootPath = _webHostEnvironment.WebRootPath;
                string dateFolder = DateTime.Now.ToString("yyyyMMdd");
                string userFolder = userid.ToString();
                string relativeDirPath = Path.Combine("images", userFolder, dateFolder);
                string absoluteDirPath = Path.Combine(wwwrootPath, relativeDirPath);

                // 确保目录存在
                if (!Directory.Exists(absoluteDirPath))
                {
                    Directory.CreateDirectory(absoluteDirPath);
                }

                // 生成文件名 guid.扩展名
                string fileName = $"{Guid.NewGuid()}{fileExtension}";
                string absoluteFilePath = Path.Combine(absoluteDirPath, fileName);
                string relativeFilePath = Path.Combine(relativeDirPath, fileName).Replace("\\", "/"); // 使用Web路径格式

                // 保存文件
                using (var stream = new FileStream(absoluteFilePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 创建数据库记录
                var imageEntity = new ImagesEntity
                {
                    File_name = file.FileName,
                    File_path = relativeFilePath,
                    File_size = (int)file.Length,
                    Upload_time = DateTime.Now,
                    Is_deleted = false,
                    Sys_Upload_Type = sysUploadType,
                    // 以下是继承自BaseEntity的属性
                    Createtime = DateTime.Now,
                    Updatetime = DateTime.Now,
                    Createuserid = userid,
                    Updateuserid = userid,
                    // 来自TenantBaseEntity的属性
                    Tenant_id = tenantid
                };

                // 保存到数据库并获取带有ID的实体
                var savedEntity = await AddEntityAsync(imageEntity);

                // 返回结果
                return new ImagesRes
                {
                    Id = savedEntity.Id,
                    FileName = savedEntity.File_name,
                    FilePath = savedEntity.File_path,
                    Url = $"/{savedEntity.File_path}", // 前端显示用的URL
                    FileSize = savedEntity.File_size,
                    UploadTime = savedEntity.Upload_time,
                    UploadType = savedEntity.Sys_Upload_Type
                };
            }
            catch (Exception ex)
            {
                _logger.Error($"上传图片失败: {ex.Message}", ex);
                throw;
            }
        }
    }
}
